package com.bodacn.packapp;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;




/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentBoxRule extends Fragment implements View.OnClickListener{

    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    public static final int msgFocusBarcode = 1001;
    public static final int msgDetailOver=1002;
    public static final int msgSizeOver=1003;
    public static final int msgRuleOver=1004;
    public static final int msgMidRuleSaveOver=1005;
    public static final int msgMidRuleDelte=1006;

    private static final int MSG_ERROR=9001;
    //全局变量
    Toast curToast;
    String curDepart,curDepartNo,curLoginUserNo,curLoginUser,curServiceUrl="",curTermNo="00000",curServiceDir,CPUID;
    String PrBarcode;
    Button btn_delete,btn_find,btn_Return;
    //Measure
    EditText view_realMeasure,edt_PO,edt_ITEM;
    Button view_affirmBtn, view_clearBtn, view_submitBtn,view_cancelBtn;
    Button view_oneBtn, view_twoBtn, view_threeBtn, view_fourBtn, view_fiveBtn, view_sixBtn, view_sevenBtn, view_eightBtn, view_nineBtn, view_zeroBtn, view_delBtn, view_pointBtn;
    ListView detailList;
    GridView ruleGrid;
    LinearLayout listhead;
    JSONArray detailJSON,sizeJSON,ruleJSON,resultJson;
    RadioGroup radioColGroup,radioDirGroup;
    RadioButton radioCol1,radioCol2,radioCol3,radioCol4;
    RadioButton radioDirHor,radioDirVer;
    EditText edt_PackWidth;
    EditText curEdit;
    int curRulePostion =-1;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentBoxRule() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerBoxRule(new MainActivity.OnTransParamsListenerBoxRule() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d("FragmentC","LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            curTermNo=mParams.get("TermNo").toString();
                            Log.d("FragmentC","LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.sendMessage(msg);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_boxrule, container, false);
        InitView(root);
        System.out.println("fragment_boxrule_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        radioColGroup=view.findViewById(R.id.radioColGroup);
        radioDirGroup=view.findViewById(R.id.radioDirGroup);
        radioCol1=view.findViewById(R.id.radioCol1);
        radioCol2=view.findViewById(R.id.radioCol2);
        radioCol3=view.findViewById(R.id.radioCol3);
        radioCol4=view.findViewById(R.id.radioCol4);
        radioDirHor=view.findViewById(R.id.radioDirHor);
        radioDirVer=view.findViewById(R.id.radioDirVer);
        edt_PO=view.findViewById(R.id.edt_PO);
        edt_ITEM=view.findViewById(R.id.edt_ITEM);
        edt_PackWidth=view.findViewById(R.id.edt_PackWidth);
        edt_PackWidth.setOnClickListener(this);
        detailList=view.findViewById(R.id.detailList);
        listhead=view.findViewById(R.id.listhead);
        ruleGrid =view.findViewById(R.id.ruleGrid);
        ruleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("ruleGrid");
                curRulePostion=position;
                edt_PackWidth.setBackgroundColor(getResources().getColor(R.color.transparent));
                curEdit=null;
                try {
                    if (ruleJSON.length()>curRulePostion)
                        view_realMeasure.setText(ruleJSON.optJSONObject(position).getString("Height"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        view_realMeasure=view.findViewById(R.id.view_realMeasure);
        btn_find=view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_delete=view.findViewById(R.id.btn_delete);
        btn_delete.setOnClickListener(this);
        btn_Return=view.findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        view_affirmBtn = (Button) view.findViewById(R.id.view_affirmBtn);
        view_affirmBtn.setOnClickListener(this);
        view_clearBtn = (Button) view.findViewById(R.id.view_clearBtn);
        view_clearBtn.setOnClickListener(this);
        view_submitBtn = (Button) view.findViewById(R.id.view_submitBtn);
        view_submitBtn.setOnClickListener(this);
        view_cancelBtn = (Button) view.findViewById(R.id.view_cancelBtn);
        view_cancelBtn.setOnClickListener(this);
        view_oneBtn = (Button) view.findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn = (Button) view.findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn = (Button) view.findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn = (Button) view.findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn = (Button) view.findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn = (Button) view.findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn = (Button) view.findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn = (Button) view.findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn = (Button) view.findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn = (Button) view.findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_delBtn = (Button) view.findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_pointBtn = (Button) view.findViewById(R.id.view_pointBtn);
        view_pointBtn.setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }


    //正式扫描;
    private void searchDetail(String paramPO, String paramItem, String paramOperType)
    {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_MidRuleQuery @OperType='"+paramOperType+"',@PO='"+paramPO+"',@Item='"+paramItem+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.edt_PackWidth:
                curEdit=edt_PackWidth;
                curEdit.setBackgroundColor(getResources().getColor(R.color.paleturquoise));
                break;
            case R.id.btn_find:
                if (edt_PO.getText().toString().length()==0){
                    curToast.setText("请先输入PO号及Item再过滤!");
                    curToast.show();
                    return;
                }
                System.out.println("enter r.id.btn_find");
                try {
                    detailJSON=new JSONArray("[]");
                    sizeJSON=new JSONArray("[]");
                    ruleJSON=new JSONArray("[]");
                    curRulePostion=-1;
                    //清除界面显示内容;
                    final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                    detailList.setAdapter(detailListAdapter);
                    //清除界面显示内容;
                    final RuleGridAdapter ruleGridAdapter = new RuleGridAdapter(getActivity());
                    ruleGrid.setAdapter(ruleGridAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                searchDetail(edt_PO.getText().toString(),edt_ITEM.getText().toString(),"Rule");
                break;
            case R.id.btn_delete:
                searchDetail(edt_PO.getText().toString(),edt_ITEM.getText().toString(),"DeleteRule");
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = (Button) v.findViewById(v.getId());
                view_realMeasure.getText().append(tmpBtn1.getText());
                if (curEdit!=null) curEdit.setText(view_realMeasure.getText().toString());
                break;
            case R.id.view_delBtn:
                if (view_realMeasure.getText().length() > 0) {
                    view_realMeasure.setSelection(view_realMeasure.getText().length());
                    int start = view_realMeasure.getSelectionStart();
                    view_realMeasure.getText().delete(start - 1, start);
                }
                if (curEdit!=null) curEdit.setText(view_realMeasure.getText().toString());
                break;
            case R.id.view_pointBtn:
                System.out.println("AindexOf:" + view_realMeasure.getText().toString().indexOf("."));
                if ((view_realMeasure.getText().toString().indexOf(".") == -1)&&(view_realMeasure.getText().toString().indexOf("/") == -1)) {
                    view_realMeasure.getText().append(".");
                }
                if (curEdit!=null) curEdit.setText(view_realMeasure.getText().toString());
                break;
            case R.id.view_clearBtn:
                view_realMeasure.setText("");
                if (curEdit!=null) curEdit.setText(view_realMeasure.getText().toString());
                break;
            case R.id.view_affirmBtn:
                if (view_realMeasure.getText().length() > 0&&curRulePostion!=-1){
                    try {
                        if (ruleJSON.length()>curRulePostion) {
                            ruleJSON.optJSONObject(curRulePostion).put("Height", view_realMeasure.getText().toString());
                        }
                        //更新修改过的行;
                        ((BaseAdapter) ruleGrid.getAdapter()).notifyDataSetChanged();
                        //只更新修改过的值;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    curToast.setText("请输入实际尺寸！");
                    curToast.show();
                }
                break;
            case R.id.view_submitBtn:
                if (ruleJSON==null||sizeJSON==null||ruleJSON.length()==0||sizeJSON.length()==0) {
                    curToast.setText("请刷新数据后重新修改保存!");
                    curToast.show();
                    return;
                }

                AlertDialog alertDialog;
                String checkStr="",tmpSize="";
                if (ruleJSON.length()>0){
                    try {
                        for (int i=0;i<ruleJSON.length();i++){
                            if (ruleJSON.optJSONObject(i).has("Height")){
                                tmpSize=ruleJSON.optJSONObject(i).getString("Size");
                                if (ruleJSON.optJSONObject(i).getString("Height").length()==0){
                                    if (checkStr.length()>0) checkStr=checkStr+","+tmpSize+"未设定高度;";
                                    else checkStr=tmpSize+"未设定高度;";
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (checkStr.length()>0){
                    alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage("数据检查未通过,"+checkStr+"请检查!")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create();
                    alertDialog.show(); // 显示对话框
                    return;
                }

                if (edt_PackWidth.getText().toString().length()==0) {
                    alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage("请输入包装宽度!")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create();
                    alertDialog.show(); // 显示对话框
                    return;
                }
                //栋数
                String paramColNum="1",paramDir="Hor";
                String OrderNo="",StyleNo="",PO="",Item="";

                if (radioCol1.isChecked()==true) paramColNum="1";
                if (radioCol2.isChecked()==true) paramColNum="2";
                if (radioCol3.isChecked()==true) paramColNum="3";
                if (radioCol4.isChecked()==true) paramColNum="4";
                if (radioDirHor.isChecked()==true) paramDir="Hor";
                if (radioDirVer.isChecked()==true) paramDir="Ver";
                //保存数据
                try {
                    if (sizeJSON.optJSONObject(0).has("OrderNo"))
                        OrderNo=sizeJSON.optJSONObject(0).getString("OrderNo");
                    if (sizeJSON.optJSONObject(0).has("StyleNo"))
                        StyleNo=sizeJSON.optJSONObject(0).getString("StyleNo");
                    if (sizeJSON.optJSONObject(0).has("PO"))
                        PO=sizeJSON.optJSONObject(0).getString("PO");
                    if (sizeJSON.optJSONObject(0).has("Item"))
                        Item=sizeJSON.optJSONObject(0).getString("Item");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                SaveRuleData(OrderNo,StyleNo,PO,Item,paramColNum,paramDir,edt_PackWidth.getText().toString());
                break;
            case R.id.view_cancelBtn:
                break;
            default:
                break;
        }
    }


    //保存工序安排
    private synchronized void SaveRuleData(final String paramOrderNo, final String paramStyleNo,
                              final String paramPO, final String paramItem,
                              final String paramColNum, final String paramDir, final String paramPackWidth) {
        if (ruleJSON==null||sizeJSON==null) return;

        //线程直接保存不经过WebService;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String BoxRuleID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    String Size="",Height="";
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement("Insert into AutoBoxRuleDeMidTable(BoxRuleDeID,BoxRuleID,Size,Height)values(newid(),?,?,?)");
                    for (int i = 0; i < ruleJSON.length(); i++) {
                        if (ruleJSON.getJSONObject(i).has("Size")) Size=ruleJSON.getJSONObject(i).getString("Size");
                        if (ruleJSON.getJSONObject(i).has("Height")) Height=ruleJSON.getJSONObject(i).getString("Height");
                        pstmt.setString(1, BoxRuleID);
                        pstmt.setString(2, Size);
                        pstmt.setString(3, Height);
                        pstmt.executeUpdate();
                    }
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec KeyPoint_Pack_MidRuleSaveTrans @OperType='MidRuleSave',@BoxRuleID='" + BoxRuleID + "',@OrderNo='"+paramOrderNo+"',@StyleNo='"+paramStyleNo
                            +"',@PO='"+paramPO+"',@Item='"+paramItem+"',@BoxCol='"+paramColNum+"',@BoxDir='"+paramDir+"',@PackWidth='"+paramPackWidth+"',@UserNo='"+curLoginUserNo+"',@UserName='"+curLoginUser+"'";
                    ReadSQLData(SqlComm);
                    Log.d("MidRuleSaveTrans","KeyPoint_Pack_MidRuleSaveTrans-----------------------------------------Over");
                } catch (SQLException | JSONException ex) {
                    ex.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo","保存试装箱规则过程出错!"+ex.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

        Log.d("SaveDaliyCount","SaveDaliyCount-----------------------------------------Over");
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case msgMidRuleDelte:
                    case msgMidRuleSaveOver:
                        try {
                            if (resultJson.length()>0){
                                if (resultJson.optJSONObject(0).has("HintInfo")){
                                    curToast.setText(resultJson.optJSONObject(0).getString("HintInfo"));
                                    curToast.show();
                                }
                                if (resultJson.optJSONObject(0).has("ErrInfo")){
                                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                            .setTitle(getString(R.string.SystemHint)).setMessage(resultJson.optJSONObject(0).getString("ErrInfo"))
                                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {

                                                }
                                            }).create();
                                    alertDialog.show(); // 显示对话框
                                }
                            }
                        } catch (JSONException e){
                            e.printStackTrace();
                        }

                        break;
                    case MSG_ERROR:
                        Bundle bundle1=msg.getData();
                        curToast.setText(bundle1.getString("HintInfo"));
                        curToast.show();
                        break;
                    case msgSizeOver:
                        if (sizeJSON!=null&&sizeJSON.length()>0){
                            try {
                                if (sizeJSON.optJSONObject(0).has("HintInfo")){
                                    curToast.setText(sizeJSON.optJSONObject(0).getString("HintInfo"));
                                    curToast.show();
                                }
                                if (sizeJSON.optJSONObject(0).has("Size1")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size1)).setText(sizeJSON.optJSONObject(0).getString("Size1"));
                                } else ((TextView)listhead.findViewById(R.id.item_Size1)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size2")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size2)).setText(sizeJSON.optJSONObject(0).getString("Size2"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size2)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size3")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size3)).setText(sizeJSON.optJSONObject(0).getString("Size3"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size3)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size4")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size4)).setText(sizeJSON.optJSONObject(0).getString("Size4"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size4)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size5")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size5)).setText(sizeJSON.optJSONObject(0).getString("Size5"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size5)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size6")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size6)).setText(sizeJSON.optJSONObject(0).getString("Size6"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size6)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size7")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size7)).setText(sizeJSON.optJSONObject(0).getString("Size7"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size7)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size8")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size8)).setText(sizeJSON.optJSONObject(0).getString("Size8"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size8)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size9")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size9)).setText(sizeJSON.optJSONObject(0).getString("Size9"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size9)).setText("");
                                if (sizeJSON.optJSONObject(0).has("Size10")) {
                                    ((TextView)listhead.findViewById(R.id.item_Size10)).setText(sizeJSON.optJSONObject(0).getString("Size10"));
                                }else ((TextView)listhead.findViewById(R.id.item_Size10)).setText("");

                                if (sizeJSON.optJSONObject(0).has("BoxCol")) {
                                    ((RadioButton)radioColGroup.findViewById(R.id.radioCol1)).setChecked(sizeJSON.optJSONObject(0).getString("BoxCol").equals("1"));
                                    ((RadioButton)radioColGroup.findViewById(R.id.radioCol2)).setChecked(sizeJSON.optJSONObject(0).getString("BoxCol").equals("2"));
                                    ((RadioButton)radioColGroup.findViewById(R.id.radioCol3)).setChecked(sizeJSON.optJSONObject(0).getString("BoxCol").equals("3"));
                                    ((RadioButton)radioColGroup.findViewById(R.id.radioCol4)).setChecked(sizeJSON.optJSONObject(0).getString("BoxCol").equals("4"));
                                }
                                if (sizeJSON.optJSONObject(0).has("BoxDir")) {
                                    ((RadioButton)radioDirGroup.findViewById(R.id.radioDirHor)).setChecked(sizeJSON.optJSONObject(0).getString("BoxDir").equals("Hor"));
                                    ((RadioButton)radioDirGroup.findViewById(R.id.radioDirVer)).setChecked(sizeJSON.optJSONObject(0).getString("BoxDir").equals("Ver"));
                                }
                                if (sizeJSON.optJSONObject(0).has("PackWidth")) {
                                    edt_PackWidth.setText(sizeJSON.optJSONObject(0).getString("PackWidth"));
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    case msgRuleOver:
                        //显示预排单;
                        if (ruleJSON!=null&&ruleJSON.length()>0){
                            if (ruleJSON.optJSONObject(0).has("HintInfo")){
                                try {
                                    curToast.setText(ruleJSON.optJSONObject(0).getString("HintInfo"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                curToast.show();
                            }
                        }
                        searchDetail(edt_PO.getText().toString(),edt_ITEM.getText().toString(),"Detail");
                        final RuleGridAdapter sizeGridAdapter = new RuleGridAdapter(getActivity());
                        ruleGrid.setAdapter(sizeGridAdapter);
                        break;
                    case msgDetailOver:
                        //显示预排单;
                        if (detailJSON!=null&&detailJSON.length()>0){
                            if (detailJSON.optJSONObject(0).has("HintInfo")){
                                try {
                                    curToast.setText(detailJSON.optJSONObject(0).getString("HintInfo"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                curToast.show();
                            }
                        }
                        searchDetail(edt_PO.getText().toString(),edt_ITEM.getText().toString(),"Size");
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailList.setAdapter(detailListAdapter);
                        break;

                    default:
                        break;
                }
            }
        }
    };

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    Message msg = new Message();
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.length()>0) {
                            if (OperType.equals("Detail")){
                                detailJSON = jsonArray;
                                msg.what = msgDetailOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else if (OperType.equals("Rule")) {
                                ruleJSON = jsonArray;
                                msg.what = msgRuleOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("Size")){
                                sizeJSON=jsonArray;
                                msg.what = msgSizeOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("MidRuleSave")){
                                resultJson=jsonArray;
                                msg.what = msgMidRuleSaveOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            //删除
                            else if (OperType.equals("DeleteRule")){
                                resultJson=jsonArray;
                                msg.what = msgMidRuleDelte;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    } else{
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo","未返回任何值");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        fragmentHandler.removeMessages(errmsg.what);
                        fragmentHandler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }

        };
        new Thread(run).start();

    }



    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_boxrule_listitem, null, false);
            int color = getResources().getColor(R.color.text_blue);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.item_FM);// 显示文字
                if (detailJSON.optJSONObject(position).has("FM"))
                    tv.setText(detailJSON.optJSONObject(position).get("FM").toString());
                tv = (TextView) convertView.findViewById(R.id.item_TO);// 显示文字
                if (detailJSON.optJSONObject(position).has("TO"))
                    tv.setText(detailJSON.optJSONObject(position).get("TO").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size1);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size1"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size1").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size2);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size2"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size2").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size3);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size3"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size3").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size4);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size4"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size4").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size5);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size5"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size5").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size6);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size6"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size6").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size7);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size7"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size7").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size8);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size8"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size8").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size9);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size9"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size9").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Size10);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size10"))
                    tv.setText(detailJSON.optJSONObject(position).get("Size10").toString());
                tv = (TextView) convertView.findViewById(R.id.item_CTM);// 显示文字
                if (detailJSON.optJSONObject(position).has("CTM"))
                    tv.setText(detailJSON.optJSONObject(position).get("CTM").toString());
                tv = (TextView) convertView.findViewById(R.id.item_PCS);// 显示文字
                if (detailJSON.optJSONObject(position).has("PCS"))
                    tv.setText(detailJSON.optJSONObject(position).get("PCS").toString());
                tv = (TextView) convertView.findViewById(R.id.item_OwenNum);// 显示文字
                if (detailJSON.optJSONObject(position).has("OwenNum"))
                    tv.setText(detailJSON.optJSONObject(position).get("OwenNum").toString());
                tv = (TextView) convertView.findViewById(R.id.item_CartonLength);// 显示文字
                if (detailJSON.optJSONObject(position).has("CartonLength"))
                    tv.setText(detailJSON.optJSONObject(position).get("CartonLength").toString());
                tv = (TextView) convertView.findViewById(R.id.item_CartonWidth);// 显示文字
                if (detailJSON.optJSONObject(position).has("CartonWidth"))
                    tv.setText(detailJSON.optJSONObject(position).get("CartonWidth").toString());
                tv = (TextView) convertView.findViewById(R.id.item_CartonHeight);// 显示文字
                if (detailJSON.optJSONObject(position).has("CartonHeight"))
                    tv.setText(detailJSON.optJSONObject(position).get("CartonHeight").toString());
                tv = (TextView) convertView.findViewById(R.id.item_CartonWeight);// 显示文字
                if (detailJSON.optJSONObject(position).has("CartonWeight"))
                    tv.setText(detailJSON.optJSONObject(position).get("CartonWeight").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }

    //订单表格适配器;
    public final class RuleGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public RuleGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return ruleJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return ruleJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_boxrule_sizeitem, null, false);
            int pullVatListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(50)));
            int color = getResources().getColor(R.color.text_blue);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.item_Size);// 显示文字
                tv.setText(ruleJSON.optJSONObject(position).get("Size").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Height);// 显示文字
                tv.setText(ruleJSON.optJSONObject(position).get("Height").toString());

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","RuleGridAdapter_position:"+position);
            return convertView;
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }


}
